package com.dragon.mmochat.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.model.role.MmochatTempNpc;
import com.dragon.mmochat.model.task.MmochatTempTask;

public class MmochatSerialDao extends SimpleJdbcDaoSupport {
	private static final SerialRowMapper roleMapper = new SerialRowMapper();

	// 初始化序列号
	private static final String getSerialSql = "select * from serial";

	public void initSerial() {
		decreaseTempTaskSerial(1000);
		decreaseBossSerial(1000);
		List<SerialClub> serialClubList = getSimpleJdbcTemplate().query(
				getSerialSql, roleMapper);
		MmochatTempTask.initSerial(serialClubList.get(0)
				.getTempTaskSerialValue());
		MmochatTempNpc.initSerial(serialClubList.get(0).getBossSerialValue());
	}

	// 更新临时任务序列号
	private static final String decreaseTempTaskSerialSql = "update serial set "
			+ "tmp_task_serial = tmp_task_serial - ?";

	public void decreaseTempTaskSerial(int delta) {
		getSimpleJdbcTemplate().update(decreaseTempTaskSerialSql, delta);
	}

	// 更新BOSS序列号
	private static final String decreaseBossSerialSql = "update serial set "
			+ "boss_serial = boss_serial - ?";

	public void decreaseBossSerial(int delta) {
		getSimpleJdbcTemplate().update(decreaseBossSerialSql, delta);
	}

	// 更新所有序列号
	private static final String updateSerialSql = "update serial set "
			+ "boss_serial = ?, tmp_task_serial = ?";

	public void updateSerial(int bossId, int taskId) {
		getSimpleJdbcTemplate().update(updateSerialSql, bossId, taskId);
	}

	public int commonUpdate(String sql) {
		return getSimpleJdbcTemplate().update(sql);
	}

	public List<SerialClub> commonQuery(String sql) {
		return getSimpleJdbcTemplate().query(sql, roleMapper);
	}

	public SerialClub commonQueryForObject(String sql) {
		return getSimpleJdbcTemplate().queryForObject(sql, roleMapper);
	}

	public static class SerialClub {
		private int tempTaskSerialValue = -1;
		private int bossSerialValue = -1;

		public int getTempTaskSerialValue() {
			return tempTaskSerialValue;
		}

		public void setTempTaskSerialValue(int tempTaskSerialValue) {
			this.tempTaskSerialValue = tempTaskSerialValue;
		}

		public int getBossSerialValue() {
			return bossSerialValue;
		}

		public void setBossSerialValue(int bossSerialValue) {
			this.bossSerialValue = bossSerialValue;
		}

	}

	static class SerialRowMapper implements ParameterizedRowMapper<SerialClub> {
		@Override
		public SerialClub mapRow(ResultSet rs, int rowNum) throws SQLException {
			SerialClub serialClub = new SerialClub();
			serialClub.setTempTaskSerialValue(rs.getInt("tmp_task_serial"));
			serialClub.setBossSerialValue(rs.getInt("boss_serial"));
			return serialClub;
		}
	}
}
